package org.xhy.hrm.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.RabbitListenerContainerFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.xhy.hrm.constants.MQConstants;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class MQConfig {

    //配置死信交换机
    @Bean
    public Exchange killDelayExchange(){
        return ExchangeBuilder.topicExchange(MQConstants.NAME_EXCHANGE_KILL_DIE_TOPIC).build();
    }

    //配置死信队列
    @Bean
    public Queue dieQueue(){
        return new Queue(MQConstants.NAME_QUEUE_KILL_DIE_ORDER);
    }

    //配置延迟队列
    @Bean
    public Queue delayQueue(){
        Map<String,Object> map = new HashMap<>();
        map.put("x-dead-letter-exchange", MQConstants.NAME_EXCHANGE_KILL_DIE_TOPIC);    //过期的消息给哪个交换机的名字
        map.put("x-dead-letter-routing-key", "killcoursedie.order");   //死信交换机把消息个哪个个routingkey
        map.put("x-message-ttl", 900000);    //队列过期时间15分钟
        return new Queue(MQConstants.NAME_QUEUE_KILL_DELAY_ORDER,true,false,false,map);
    }

    //绑定死信队列
    @Bean
    public Binding bindingDieQueue(){
        return BindingBuilder.bind(dieQueue()).to(killDelayExchange())
                .with("killcoursedie.order").noargs();
    }

    //绑定延迟队列
    @Bean
    public Binding bindingDelayQueue(){
        return BindingBuilder.bind(delayQueue()).to(killDelayExchange())
                .with("killcoursedelay.order").noargs();
    }

    //自定义RabbitTemplate
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        //如果消息发送到MQ失败，把消息返回回来
        rabbitTemplate.setMandatory(true);
        return rabbitTemplate;
    }

    //配置监听器的容器工厂
    @Bean("rabbitListenerContainerFactory")
    public RabbitListenerContainerFactory<?> rabbitListenerContainerFactory(ConnectionFactory connectionFactory){
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setMessageConverter(new Jackson2JsonMessageConverter());
        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        factory.setPrefetchCount(1);
        return factory;
    }
}
